package cn.xyy.web.satoken;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaStrategy;

/**
 * 拦截器，优先执行，验证用户是否登录
 * 
 * @author xyy
 *
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
	static List<String> exclude = new ArrayList<String>();
	static {
		exclude.add("/favicon.ico");
		exclude.add("/rest/auth/login");
		exclude.add("/rest/sysfile/");
		exclude.add("/public/rest/");
		exclude.add("/index.html");
		exclude.add("/static");
		exclude.add("/error");
	}

	private boolean permitUrl(String requestURL) {
		for (String url : exclude) {
			if (requestURL.startsWith(url) || "/".equals(requestURL)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (permitUrl(request.getRequestURI())) {
			return true;
		}

		// 2. 校验@Ignore或者@Inner
		if (handler instanceof HandlerMethod) {
			// 获取此请求对应的 Method 处理函数
			Method method = ((HandlerMethod) handler).getMethod();
			// 如果此 Method 或其所属 Class 标注了 @Ignore 则忽略掉登录校验
			if (SaStrategy.me.isAnnotationPresent.apply(method, SaIgnore.class)) {
				return true;
			}

		}

		// 3.校验是否登录
		StpUtil.checkLogin();
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) throws Exception {
	}
}
